<template>
  <div class="marketing-video-generate">
    <!-- 使用引导提示 -->
    <div v-if="showGuide" class="guide-tip">
      <div class="guide-content">
        <div class="guide-icon">💡</div>
        <div class="guide-text">
          <strong>使用步骤：</strong>上传图片或选择数字人 → 上传产品图片 → 编辑营销文案 → 生成视频
        </div>
      </div>
    </div>

    <!-- 顶部进度条 -->
    <div class="progress-bar">
      <div class="step-item" :class="{ active: currentStep === 1, completed: currentStep > 1 }">
        <div class="step-number">1</div>
        <div class="step-text">选择数字人和产品图片</div>
      </div>
      <div class="step-item" :class="{ active: currentStep === 2, completed: currentStep > 2 }">
        <div class="step-number">2</div>
        <div class="step-text">编辑营销文案</div>
      </div>
      <div class="step-item" :class="{ active: currentStep === 3, completed: currentStep > 3 }">
        <div class="step-number">3</div>
        <div class="step-text">生成视频</div>
      </div>
      <div class="step-item" :class="{ active: currentStep === 4 }">
        <div class="step-number">4</div>
        <div class="step-text">完成</div>
      </div>
    </div>

    <!-- 步骤1：选择数字人和产品图片 -->
    <div v-if="currentStep === 1" class="step-content">
      <div class="main-content">
        <!-- 左侧选择区域 -->
        <div class="left-panel">
          <!-- 标题和生成记录按钮 -->
          <div class="section-header">
            <h2 class="section-title">生成营销视频</h2>
            <h2 class="section-title records-title" @click="handleGoToRecords">
              <el-icon><Document /></el-icon>
              生成记录
            </h2>
          </div>
          
          <!-- 分类选择 -->
          <div class="category-tabs">
            <div class="category-list">
              <div
                v-for="category in categories"
                :key="category.value"
                class="category-item"
                :class="{ active: activeCategory === category.value }"
                @click="handleTabChange(category.value)"
              >
                {{ category.label }}
              </div>
            </div>
            
            <!-- 人种选择 -->
            <div class="ethnicity-section">
              <h4 class="section-subtitle">人种筛选</h4>
              <div class="ethnicity-list">
                <!-- 如果正在加载或人种列表为空，显示加载中 -->
                <div v-if="ethnicityLoading || ethnicityList.length === 0" class="category-item disabled">
                  {{ ethnicityLoading ? '加载中...' : '暂无人种分类' }}
                </div>
                <!-- 所有分类选项 -->
                <div 
                  v-if="ethnicityList.length > 0"
                  class="category-item"
                  :class="{ active: activeEthnicity === 'all' }"
                  @click="handleEthnicityChange('all')"
                >
                  所有
                </div>
                <!-- 人种列表 -->
                <div 
                  v-for="ethnicity in ethnicityList" 
                  :key="ethnicity.ethnicityId" 
                  class="category-item"
                  :class="{ active: activeEthnicity === ethnicity.ethnicityId }"
                  @click="handleEthnicityChange(ethnicity.ethnicityId)"
                >
                  {{ ethnicity.ethnicityName }}
                </div>
              </div>
            </div>
            
            <div class="avatar-grid" ref="avatarGridRef" @scroll="handleScroll">
              <!-- 上传自己的照片卡片 -->
              <div class="upload-card" 
                :class="{ active: selectedAvatar?.isCustom }" 
                @click.stop="triggerFileSelect"
              >
                <div v-if="!selectedAvatar?.isCustom" class="upload-content">
                  <el-icon :size="32"><Plus /></el-icon>
                  <span>使用我的照片</span>
                </div>
                <div v-else class="custom-avatar-preview">
                  <img :src="selectedAvatar.imageUrl" :alt="selectedAvatar.name" class="avatar-image" />
                  <div class="avatar-info">
                    <span class="avatar-name">{{ selectedAvatar.name }}</span>
                    <el-tag size="small" type="success">自定义</el-tag>
                  </div>
                  <div class="change-photo-overlay">
                    <el-icon :size="20"><Edit /></el-icon>
                    <span>更换照片</span>
                  </div>
                </div>
              </div>
              <!-- 数字人列表 -->
              <div
                v-for="avatar in allAvatars"
                :key="avatar.id"
                class="avatar-item"
                :class="{ active: selectedAvatar?.id === avatar.id && !selectedAvatar?.isCustom }"
                @click="handleSelectAvatar(avatar)"
              >
                <img :src="avatar.imageUrl" :alt="avatar.name" class="avatar-image" />
              </div>
              <!-- 加载更多提示 -->
              <div v-if="isLoading" class="loading-more">
                <el-icon class="loading-icon"><Loading /></el-icon>
                <span>加载中...</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧预览区域 -->
        <div class="right-panel">
          <div class="preview-section">
            <h3>上传产品图片</h3>
            <div class="preview-container">
              <div v-if="!selectedImage?.url" class="upload-placeholder" @click.stop="triggerProductUpload">
                <el-icon :size="48"><Upload /></el-icon>
                <div class="upload-text">上传产品图片</div>
                <div class="upload-hint">支持 JPG、PNG、BMP、WebP 格式</div>
              </div>
              <div v-else class="image-wrapper">
                <img :src="selectedImage.url" class="preview-image"/>
              </div>
            </div>
            <div class="action-buttons">
              <el-button v-if="selectedImage" type="danger" @click="resetProductImage">重新上传</el-button>
              <el-button 
                type="primary" 
                :disabled="!canProceedStep1"
                @click="nextStep"
                class="next-btn"
              >
                下一步
                <span class="points-text">11积分</span>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 步骤2：编辑脚本 -->
    <div v-if="currentStep === 2" class="step-content">
      <div class="main-content">
        <!-- 左侧预览区域 -->
        <div class="left-panel">
          <div class="result-preview-section">
            <h3>生成结果预览</h3>
            <div class="preview-container">
              <div v-if="generatedImage" class="image-container">
                <img 
                  :src="generatedImage" 
                  style="max-width: 100%; width: auto; height: auto; display: block;"
                />
              </div>
              <div v-else class="no-preview">暂无预览图</div>
            </div>
          </div>
        </div>

        <!-- 右侧编辑区域 -->
        <div class="right-panel">
          <div class="edit-section">
            <div class="script-header">
              <h3>营销文案编辑</h3>
              <el-button-group>
                <el-button 
                  :type="scriptMode === 'tts' ? 'primary' : 'default'" 
                  @click="scriptMode = 'tts'"
                >
                  文本转语音
                </el-button>
                <el-button 
                  :type="scriptMode === 'audio' ? 'primary' : 'default'" 
                  @click="handleSwitchToAudio"
                >
                  导入音频
                </el-button>
              </el-button-group>
            </div>
            
            <!-- 文本转语音模式 -->
            <template v-if="scriptMode === 'tts'">
              <div class="voice-select-wrapper">
                <div 
                  class="voice-select-btn" 
                  @click="handleVoiceSelect"
                >
                  <span>{{ voiceList.find(v => v.voiceId === voiceoverId)?.voiceName || '选择音色' }}</span>
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </div>
              <el-input
                v-model="ttsText"
                type="textarea"
                :rows="24"
                placeholder="请输入口播内容..."
                class="tts-textarea"
              />
            </template>

            <!-- 导入音频模式 -->
            <template v-else>
              <div class="audio-upload-section">
                <input
                  type="file"
                  accept=".mp3,.wav"
                  class="file-input"
                  ref="audioInputRef"
                  @change="handleAudioSelect"
                />
                <div v-if="!previewAudio" class="upload-placeholder" @click="triggerAudioSelect">
                  <el-icon size="32"><Upload /></el-icon>
                  <div class="upload-text">点击上传音频文件</div>
                  <div class="upload-hint">支持 MP3、WAV 格式</div>
                </div>
                <div v-else class="audio-preview">
                  <div class="audio-info">
                    <el-icon><Document /></el-icon>
                    <span class="audio-name">{{ previewAudio.fileName }}</span>
                  </div>
                  <audio controls :src="previewAudio.url" class="audio-player"></audio>
                  <div class="audio-actions">
                    <el-button type="danger" @click="resetAudioUpload">重新上传</el-button>
                  </div>
                </div>
              </div>
            </template>

            <!-- 生成模式选择 -->
            <div class="mode-select">
              <el-radio-group v-model="videoMode" size="small">
                <el-radio
                  v-for="option in modeOptions"
                  :key="option.value"
                  :label="option.value"
                >
                  {{ option.label }}
                </el-radio>
              </el-radio-group>
              <el-tooltip
                content="轻量模式：11积分&#10;高级模式：14积分&#10;数字人模式：每秒1积分"
                placement="top"
                :show-after="100"
              >
                <el-icon class="help-icon"><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button 
                type="primary" 
                :loading="isGenerating"
                :disabled="!canProceedStep2"
                @click="handleGenerateVideo"
              >
                {{ isGenerating ? '生成中...' : '开始生成' }}
              </el-button>
              
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 步骤3：生成中 -->
    <div v-if="currentStep === 3" class="step-content">
      <div class="generating-content">
        <div class="generating-info">
          <el-icon size="64" class="generating-icon"><Loading /></el-icon>
          <h3>正在生成营销视频...</h3>
          <p>请耐心等待，生成过程可能需要几分钟时间</p>
          <el-progress :percentage="progress" :stroke-width="8" class="progress" />
        </div>
      </div>
    </div>

    <!-- 步骤4：完成 -->
    <div v-if="currentStep === 4" class="step-content">
      <div class="completed-content">
        <div class="completed-info">
          <el-icon size="64" class="success-icon"><SuccessFilled /></el-icon>
          <h3>视频生成完成！</h3>
          <p>您的营销视频已经成功生成</p>
          
          <!-- 视频展示区域 -->
          <div v-if="finishedVideoUrl" class="video-preview-section">
            <h4>生成结果预览</h4>
            <div class="video-container">
              <video 
                :src="finishedVideoUrl"
                controls
                class="finished-video"
                preload="metadata"
              >
                您的浏览器不支持视频播放。
              </video>
            </div>
          </div>
          
          <div class="action-buttons">
            <el-button type="primary" @click="downloadVideo">
              <el-icon><Download /></el-icon>
              下载视频
            </el-button>
            <el-button @click="viewVideoList">查看视频列表</el-button>
            <el-button @click="createAnother">再生成一个</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 音色选择弹窗 -->
    <el-dialog
      v-model="showVoiceDialog"
      title="选择AI音色"
      width="80%"
      class="voice-dialog dark-mode"
      :close-on-click-modal="false"
      @open="handleVoiceDialogOpen"
      @close="handleVoiceDialogClose"
      v-if="scriptMode === 'tts'"
    >
      <div class="voice-filter">
        <el-radio-group v-model="genderFilter" class="filter-item">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button label="male">男声</el-radio-button>
          <el-radio-button label="female">女声</el-radio-button>
        </el-radio-group>
        <el-radio-group v-model="ageFilter" class="filter-item">
          <el-radio-button label="">全部年龄</el-radio-button>
          <el-radio-button label="Young">青年</el-radio-button>
          <el-radio-button label="Middle Age">中年</el-radio-button>
          <el-radio-button label="Old">老年</el-radio-button>
        </el-radio-group>
        <el-select v-model="languageFilter" placeholder="全部语言" class="filter-item language-select" style="width: 220px;" @change="handleVoiceFilterChange">
          <el-option label="全部语言" value="" />
          <el-option label="简体中文 (Simplified Chinese)" value="zh-CN" />
          <el-option label="English" value="en" />
          <el-option label="Arabic (العربية)" value="ar" />
          <el-option label="Bulgarian (Български)" value="bg" />
          <el-option label="Croatian (Hrvatski)" value="hr" />
          <el-option label="Czech (Čeština)" value="cs" />
          <el-option label="Danish (Dansk)" value="da" />
          <el-option label="Dutch (Nederlands)" value="nl" />
          <el-option label="Filipino (Filipino)" value="fil" />
          <el-option label="Finnish (Suomi)" value="fi" />
          <el-option label="French (Français)" value="fr" />
          <el-option label="German (Deutsch)" value="de" />
          <el-option label="Greek (Ελληνικά)" value="el" />
          <el-option label="Hindi (हिन्दी)" value="hi" />
          <el-option label="Hungarian (Magyar)" value="hu" />
          <el-option label="Indonesian (Bahasa Indonesia)" value="id" />
          <el-option label="Italian (Italiano)" value="it" />
          <el-option label="Japanese (日本語)" value="ja" />
          <el-option label="Korean (한국어)" value="ko" />
          <el-option label="Malay (Bahasa Melayu)" value="ms" />
          <el-option label="Norwegian (Norsk)" value="nb" />
          <el-option label="Polish (Polski)" value="pl" />
          <el-option label="Portuguese (Português)" value="pt" />
          <el-option label="Romanian (Română)" value="ro" />
          <el-option label="Russian (Русский)" value="ru" />
          <el-option label="Slovak (Slovenčina)" value="sk" />
          <el-option label="Spanish (Español)" value="es" />
          <el-option label="Swedish (Svenska)" value="sv" />
          <el-option label="Traditional Chinese (繁體中文)" value="zh-Hant" />
          <el-option label="Turkish (Türkçe)" value="tr" />
          <el-option label="Ukrainian (Українська)" value="uk" />
          <el-option label="Vietnamese (Tiếng Việt)" value="vi" />
        </el-select>
      </div>
      
      <div class="voice-grid" ref="voiceGridRef" @scroll="handleVoiceScroll">
        <div
          v-for="voice in filteredVoiceList"
          :key="voice.voiceId"
          class="voice-card"
          :class="{ active: voiceoverId === voice.voiceId }"
          @click="handleSelectVoice(voice)"
        >
          <div class="voice-info">
            <div class="voice-name">{{ voice.voiceName }}</div>
            <div class="voice-tags">
              <el-tag size="small" :type="voice.gender === 'male' ? 'info' : 'danger'">
                {{ voice.gender === 'male' ? '男声' : '女声' }}
              </el-tag>
              <el-tag size="small" type="warning">{{ voice.age }}</el-tag>
              <el-tag size="small" type="success">{{ voice.accent || '普通话' }}</el-tag>
            </div>
          </div>
          <div class="voice-preview">
            <el-button 
              type="primary" 
              size="small"
              class="preview-btn" 
              @click.stop="playVoiceDemo(voice)"
            >
              <el-icon><VideoPlay /></el-icon>
              试听
            </el-button>
          </div>
        </div>
        <div v-if="voiceLoading" class="loading-more">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showVoiceDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmVoiceSelection">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, onUnmounted, watch } from 'vue'
import { Plus, Upload, Loading, Document, VideoPlay, SuccessFilled, Edit, InfoFilled, ArrowDown, Download, QuestionFilled } from '@element-plus/icons-vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { apiRequest, API_CONFIG } from '../../config/api.js'
import axios from 'axios'

const router = useRouter()
const route = useRoute()

// 监听路由变化，包括相同路由的变化
watch(
  () => route.fullPath,
  () => {
    // 如果没有任务ID参数，说明是新建任务，重置所有状态
    if (!route.query.taskId) {
      createAnother()
    }
  }
)

// 步骤控制
const currentStep = ref(1)
const progress = ref(0)
const showGuide = ref(true)

// 步骤1数据
const activeCategory = ref('all')
const selectedAvatar = ref(null)
const selectedImage = ref(null)
const fileInputRef = ref(null)
const productFileRef = ref(null)
const allAvatars = ref([])
const pageNo = ref(0)
const pageSize = ref(20)
const total = ref(0)
const avatarGridRef = ref(null)
const isLoading = ref(false)
const hasMore = computed(() => allAvatars.value.length < total.value)
const categories = ref([
  { label: 'All', value: 'all', categoryId: '' }
])

// 人种相关数据
const ethnicityList = ref([])
const activeEthnicity = ref('all')
const ethnicityLoading = ref(false)

// 步骤2数据
// 视频生成模式
const videoMode = ref('lite')  // 默认使用 lite 模式
const modeOptions = [
  { label: '轻量模式', value: 'lite' },
  { label: '高级模式', value: 'pro' },
  { label: '数字人模式', value: 'avatar2' }
]

const scriptMode = ref('tts')
const scriptText = ref('')
const selectedVoice = ref(null)
const subtitleStyle = ref('')
const previewAudio = ref(null)
const audioInputRef = ref(null)

// 计算属性
const canProceedStep1 = computed(() => {
  return selectedAvatar.value && selectedImage.value?.url && imageEditPrompt.value.trim()
})

const canProceedStep2 = computed(() => {
  // 文本转语音模式：需要选择音色和输入文本
  if (scriptMode.value === 'tts') {
    return voiceoverId.value && ttsText.value.trim()
  }
  // 音频上传模式：需要上传音频文件
  else if (scriptMode.value === 'audio') {
    return previewAudio.value && previewAudio.value.fileId
  }
  // 默认返回 false
  return false
})

// 防抖状态
const isSelecting = ref(false)

// 在 script setup 中添加分类映射
const categoryNameMap = {
  'Jewelry': '珠宝首饰',
  'Clothing': '服装',
  'Stationery & Office Supplies': '文具办公',
  'Watches': '手表',
  'App': '应用软件',
  'Kitchenware': '厨具',
  'Cycling Accessories': '骑行配件',
  'Tools': '工具',
  'Food': '食品',
  'Large Appliances': '大型电器',
  'Maternal & Infant Products': '母婴用品',
  'Books': '图书',
  'Bags & Luggage': '箱包',
  'Drinkware': '饮水用具',
  'Footwear': '鞋类',
  'Beverages': '饮料',
  '3C Digital Products': '3C数码产品',
  'Perfume': '香水',
  'Beauty & Personal Care': '美妆个护',
  'Medication': '药品',
  'Vitamins & Supplements': '维生素和保健品',
  'General': '通用'
}

// 步骤1方法
const fetchCategories = async () => {
  console.log('开始获取分类列表...')
  try {
    const response = await apiRequest('/productAvatar/categoryList', {
      method: 'GET'
    })
    
    console.log('分类列表响应:', response)
    
    if (response.code === 200) {
      categories.value = [
        { label: '全部', value: 'all', categoryId: '' },
        ...response.data.map(item => ({
          label: categoryNameMap[item.categoryName.trim()] || item.categoryName, // 去除空格后再映射
          value: item.categoryId,
          categoryId: item.categoryId
        }))
      ]
      console.log('分类列表设置完成:', categories.value)
    } else {
      console.error('分类列表响应错误:', response)
      ElMessage.error(response.msg || response.message || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

const fetchAvatarList = async (isLoadMore = false) => {
  if (isLoading.value) return
  isLoading.value = true
  
  console.log('开始获取数字人列表...', { isLoadMore, pageNo: pageNo.value })
  
  try {
    const params = new URLSearchParams({
      pageNo: String(pageNo.value + 1),
      pageSize: String(pageSize.value)
    })

    const currentCategory = categories.value.find(cat => cat.value === activeCategory.value)
    if (currentCategory && currentCategory.categoryId) {
      params.append('categoryIds', currentCategory.categoryId)
    }

    // 添加人种参数
    if (activeEthnicity.value && activeEthnicity.value !== 'all') {
      params.append('ethnicityIds', activeEthnicity.value)
    }

    console.log('请求参数:', params.toString())

    const response = await apiRequest(`/productAvatar/resource/avatarList?${params.toString()}`, {
      method: 'GET'
    })
    
    console.log('数字人列表响应:', response)
    
    if (response.code === 200) {
      const newAvatars = response.data.data.map(item => ({
        id: item.avatarId,
        name: item.avatarId.slice(0, 8), // 使用ID的前8位作为显示名称
        gender: item.gender,
        imageUrl: item.avatarImagePath,
        voiceoverId: item.voiceoverId,
        ethnicityList: item.avatarEthnicityList,
        categoryList: item.avatarCategoryList,
        objectMaskImageInfo: item.objectMaskImageInfo,
        minSubsType: item.minSubsType
      }))
      
      console.log('处理后的数字人数据:', newAvatars)
      
      if (isLoadMore) {
        allAvatars.value = [...allAvatars.value, ...newAvatars]
      } else {
        allAvatars.value = newAvatars
      }
      
      total.value = response.data.total
      console.log('数字人列表更新完成，总数:', total.value, '当前数量:', allAvatars.value.length)
    } else {
      console.error('数字人列表响应错误:', response)
      ElMessage.error(response.msg || response.message || '获取数字人列表失败')
    }
  } catch (error) {
    console.error('获取数字人列表失败:', error)
    ElMessage.error('获取数字人列表失败')
  } finally {
    isLoading.value = false
  }
}

const handleTabChange = (tab) => {
  activeCategory.value = tab
  pageNo.value = 0
  allAvatars.value = []
  fetchAvatarList()
}

const handleSelectAvatar = (avatar) => {
  // 确保选择的是预设数字人，而不是自定义数字人
  selectedAvatar.value = { ...avatar, isCustom: false }
}

const triggerFileSelect = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.style.display = 'none'
  input.onchange = handleImageSelect
  document.body.appendChild(input)
  input.click()
  input.remove()
}

const triggerProductUpload = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.jpg,.jpeg,.png,.bmp,.webp'
  input.style.display = 'none'
  input.onchange = handleProductImageSelect
  document.body.appendChild(input)
  input.click()
  input.remove()
}

const handleImageSelect = async (event) => {
  // 重置选择状态
  isSelecting.value = false
  
  const file = event.target.files?.[0]
  if (!file) return

  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 创建本地预览URL
  const localPreviewUrl = URL.createObjectURL(file)

  // 创建自定义数字人对象，使用本地预览URL
  const customAvatar = {
    id: `custom_${Date.now()}`,
    name: '我的照片',
    gender: 'unknown',
    imageUrl: localPreviewUrl,
    voiceoverId: null,
    ethnicityList: [],
    faceSquareConfig: null,
    isCustom: true
  }

  // 选择这个自定义数字人
  selectedAvatar.value = customAvatar

  // 获取文件后缀名并转换为对应的格式
  const extension = file.name.split('.').pop()?.toLowerCase()
  let format = 'jpg'

  switch (extension) {
    case 'jpg':
    case 'jpeg':
      format = 'jpg'
      break
    case 'png':
      format = 'png'
      break
    case 'bmp':
      format = 'bmp'
      break
    case 'webp':
      format = 'webp'
      break
    default:
      ElMessage.error('不支持的图片格式，请使用 JPG、PNG、BMP 或 WebP 格式')
      URL.revokeObjectURL(localPreviewUrl)
      return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '上传照片中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 获取上传凭证
    const uploadResponse = await apiRequest(`${API_CONFIG.ENDPOINTS.GET_UPLOAD_CREDENTIAL}?format=${format}`, {
      method: 'GET'
    })

    if (uploadResponse.code !== 200) {
      throw new Error(uploadResponse.msg || uploadResponse.message || '获取上传凭证失败')
    }

    const { uploadUrl, fileId } = uploadResponse.data

    // 上传到S3
    await axios.put(uploadUrl, file, {
      headers: {
        'Content-Type': file.type
      }
    })

    // 只更新fileId，保持使用本地预览URL
    selectedAvatar.value = {
      ...selectedAvatar.value,
      fileId: fileId
    }
    
    ElMessage.success('照片上传成功！')

  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(error.message || '上传失败')
  } finally {
    loading.close()
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
  }
}

const handleProductImageSelect = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return

  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 创建本地预览URL
  const localPreviewUrl = URL.createObjectURL(file)

  // 先设置本地预览
  selectedImage.value = {
    url: localPreviewUrl,
    isLocalPreview: true
  }

  const extension = file.name.split('.').pop()?.toLowerCase()
  let format = 'jpg'

  switch (extension) {
    case 'jpg':
    case 'jpeg':
      format = 'jpg'
      break
    case 'png':
      format = 'png'
      break
    case 'bmp':
      format = 'bmp'
      break
    case 'webp':
      format = 'webp'
      break
    default:
      ElMessage.error('不支持的图片格式，请使用 JPG、PNG、BMP 或 WebP 格式')
      URL.revokeObjectURL(localPreviewUrl)
      selectedImage.value = null
      return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '上传中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const uploadResponse = await apiRequest(`${API_CONFIG.ENDPOINTS.GET_UPLOAD_CREDENTIAL}?format=${format}`, {
      method: 'GET'
    })

    if (uploadResponse.code !== 200) {
      throw new Error(uploadResponse.msg || uploadResponse.message || '获取上传凭证失败')
    }

    const { uploadUrl, fileId } = uploadResponse.data

    await axios.put(uploadUrl, file, {
      headers: {
        'Content-Type': file.type
      }
    })

    // 保持使用本地预览URL，只更新fileId
    selectedImage.value = {
      url: localPreviewUrl,
      fileId,
      isLocalPreview: true
    }

  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(error.message || '上传失败')
  } finally {
    loading.close()
    if (productFileRef.value) {
      productFileRef.value.value = ''
    }
  }
}

const resetProductImage = () => {
  if (selectedImage.value?.isLocalPreview) {
    URL.revokeObjectURL(selectedImage.value.url)
  }
  selectedImage.value = null
  if (productFileRef.value) {
    productFileRef.value.value = ''
  }
}

const handleScroll = async (e) => {
  const target = e.target
  const { scrollTop, scrollHeight, clientHeight } = target
  
  // 当滚动到距离底部50px以内时，加载更多
  const distanceToBottom = scrollHeight - scrollTop - clientHeight
  
  console.log('滚动事件触发:', {
    scrollTop,
    scrollHeight,
    clientHeight,
    distanceToBottom,
    isLoading: isLoading.value,
    hasMore: hasMore.value,
    currentCount: allAvatars.value.length,
    total: total.value
  })
  
  if (distanceToBottom < 50 && !isLoading.value && hasMore.value) {
    console.log('开始加载更多数据...')
    pageNo.value++
    await fetchAvatarList(true)
  }
}

// 步骤2方法
const handleSwitchToAudio = () => {
  scriptMode.value = 'audio'
  scriptText.value = ''
}

const triggerAudioSelect = () => {
  audioInputRef.value?.click()
}

const resetAudioUpload = () => {
  if (previewAudio.value?.url) {
    URL.revokeObjectURL(previewAudio.value.url)
  }
  previewAudio.value = null
  if (audioInputRef.value) {
    audioInputRef.value.value = ''
  }
}

const handleAudioSelect = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('audio/')) {
    ElMessage.error('请选择音频文件')
    return
  }

  // 获取文件后缀名
  const extension = file.name.split('.').pop()?.toLowerCase()
  if (!extension) {
    ElMessage.error('无法识别文件格式')
    return
  }

  // 支持的音频格式
  const supportedFormats = ['mp3', 'wav']
  
  // 检查是否是支持的格式
  if (!supportedFormats.includes(extension)) {
    ElMessage.error('不支持的音频格式，请上传 MP3 或 WAV 格式的音频文件')
    return
  }

  let format = extension

  const loading = ElLoading.service({
    lock: true,
    text: '上传音频中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const uploadResponse = await apiRequest(`/aiAvatar/getUploadCredential?format=${format}`, {
      method: 'GET'
    })

    if (uploadResponse.code !== 200) {
      throw new Error(uploadResponse.msg || uploadResponse.message || '获取上传凭证失败')
    }

    const { uploadUrl, fileId } = uploadResponse.data

    await axios.put(uploadUrl, file, {
      headers: {
        'Content-Type': file.type
      }
    })

    previewAudio.value = {
      url: URL.createObjectURL(file),
      fileId,
      fileName: file.name,
      type: file.type,
      format
    }

    ElMessage.success('音频上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(error.message || '上传失败')
  } finally {
    loading.close()
    if (audioInputRef.value) {
      audioInputRef.value.value = ''
    }
  }
}

const getVoiceList = async (isLoadMore = false) => {
  console.log('开始获取音色列表...', { isLoadMore, voicePageNo: voicePageNo.value })
  
  if (!isLoadMore) {
    voicePageNo.value = 1
    voiceHasMore.value = true
    voiceList.value = []
  }

  if (!voiceHasMore.value || voiceLoading.value) {
    console.log('跳过音色列表获取:', { voiceHasMore: voiceHasMore.value, voiceLoading: voiceLoading.value })
    return
  }

  try {
    voiceLoading.value = true
    const params = {
      pageNo: voicePageNo.value,
      pageSize: 20
    }

    if (genderFilter.value) params.gender = genderFilter.value
    if (ageFilter.value) params.age = ageFilter.value
    if (languageFilter.value) params.language = languageFilter.value

    console.log('音色列表请求参数:', params)

    const response = await apiRequest('/aiAvatar/voiceList', {
      method: 'GET',
      params
    })

    console.log('音色列表响应:', response)

    if (response && response.code === 200 && response.data) {
      const { data, total } = response.data
      
      console.log('音色数据处理:', { 
        dataLength: data?.length, 
        total, 
        isLoadMore,
        currentVoiceListLength: voiceList.value.length
      })
      
      if (isLoadMore) {
        voiceList.value = [...voiceList.value, ...data]
      } else {
        voiceList.value = data
      }

      // 判断是否还有更多数据
      voiceHasMore.value = voiceList.value.length < total
      if (voiceHasMore.value) {
        voicePageNo.value++
      }
      
      console.log('音色列表更新完成:', {
        voiceListLength: voiceList.value.length,
        total,
        voiceHasMore: voiceHasMore.value,
        nextPageNo: voicePageNo.value
      })
      
    } else {
      console.error('音色列表响应格式错误:', response)
    }
  } catch (error) {
    console.error('获取AI音色列表失败:', error)
    ElMessage.warning('获取AI音色列表失败')
  } finally {
    voiceLoading.value = false
  }
}

// 步骤控制方法
const nextStep = async () => {
  if (currentStep.value === 1) {
    try {
      const params = {
        taskName: '营销视频任务',
        productImageFileId: selectedImage.value.fileId,
        imageEditPrompt: imageEditPrompt.value
      }

      // 如果是自定义上传的数字人，传递templateImageFileId
      if (selectedAvatar.value.isCustom) {
        params.templateImageFileId = selectedAvatar.value.fileId
      } else {
        // 如果是选择的已有数字人，传递数字人ID
        params.avatarId = selectedAvatar.value.id
      }

      const response = await apiRequest('/productAvatar/task/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(params)
      })

      if (response.code !== 200) {
        throw new Error(response.msg || response.message || '创建任务失败')
      }

      // 保存任务ID
      currentTaskId.value = response.data.task_id
      ElMessage.success('任务创建成功')
      
      // 显示选项对话框
      ElMessageBox.confirm(
        '任务已开始生成，您可以选择等待生成完成或继续创建新的任务',
        '视频生成中',
        {
          confirmButtonText: '继续创建',
          cancelButtonText: '等待生成',
          type: 'info',
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
        }
      ).then(() => {
        // 用户选择继续创建，清除当前任务相关状态
        if (pollingTimer.value) {
          clearInterval(pollingTimer.value)
          pollingTimer.value = null
        }
        currentTaskId.value = null
        createAnother()
      }).catch(() => {
        // 用户选择等待生成，开始轮询任务状态
        currentStep.value = 3
        progress.value = 0
        startPolling()
      })
    } catch (error) {
      console.error('创建任务失败:', error)
      ElMessage.error(error.message || '创建任务失败，请重试')
      return
    }
  } else if (currentStep.value < 4) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--
  }
}

// 生成视频
const handleGenerateVideo = async () => {
  if (!canProceedStep2.value) {
    ElMessage.warning('请完善所有必填内容')
    return
  }

  // 检查当前状态
  if (overallStatus.value === 3) {
    ElMessage.warning('视频正在生成中，请耐心等待')
    return
  }

  try {
    isGenerating.value = true
    const params = {
      taskId: currentTaskId.value,
      selectedResultKey: productReplaceResultKey.value,
      mode: videoMode.value
    }

    // 根据模式添加不同的参数
    if (scriptMode.value === 'tts') {
      params.scriptMode = 'text'
      params.voiceoverId = voiceoverId.value
      params.ttsText = ttsText.value
    } else {
      params.scriptMode = 'video'
      params.audioFileId = previewAudio.value.fileId
    }

    const response = await apiRequest('/productAvatar/task/startVideoGeneration', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(params)
    })

    if (response.code !== 200) {
      throw new Error(response.msg || response.message || '生成失败')
    }

    currentStep.value = 3
    progress.value = 0
    overallStatus.value = 3

    // 开始轮询生成状态
    startPolling()

  } catch (error) {
    console.error('生成失败:', error)
    ElMessage.error(error.message || '生成失败，请重试')
  } finally {
    isGenerating.value = false
  }
}

// 修改轮询状态的方法
const startPolling = async () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
  }

  const checkStatus = async () => {
    try {
      const response = await apiRequest(`/productAvatar/task/detail?taskId=${currentTaskId.value}`, {
        method: 'GET'
      })

      if (response.code === 200) {
        const taskInfo = response.data
        overallStatus.value = taskInfo.overall_status

        if (overallStatus.value === 2) {
          // 图片生成完成，进入步骤2（填写营销文案）
          clearInterval(pollingTimer.value)
          currentStep.value = 2
          progress.value = 50
          
          // 设置生成的图片数据
          if (taskInfo.result_images) {
            if (Array.isArray(taskInfo.result_images) && taskInfo.result_images.length > 0) {
              const firstResult = taskInfo.result_images[0]
              if (firstResult && typeof firstResult === 'object') {
                productReplaceResultKey.value = firstResult.imageId || ''
                // 处理图片URL，添加尺寸限制参数
                generatedImage.value = `${firstResult.url}?x-oss-process=image/resize,m_fill,h_200,w_200`
              }
            }
          }
          
          ElMessage.success('图片生成完成，请填写营销文案')
        } else if (overallStatus.value === 4) {
          // 视频生成完成
          clearInterval(pollingTimer.value)
          currentStep.value = 4
          progress.value = 100
          
          // 设置生成的视频URL
          if (taskInfo.finished_video_url) {
            finishedVideoUrl.value = taskInfo.finished_video_url
          }
          
          ElMessage.success('视频生成完成！')
        } else if (overallStatus.value === 3) {
          // 更新进度
          progress.value = taskInfo.progress || 0
        } else if (overallStatus.value === 5) {
          // 生成失败
          clearInterval(pollingTimer.value)
          const errorMsg = taskInfo.error_msg || taskInfo.error_message || '视频生成失败'
          ElMessage.error(errorMsg)
        }
      }
    } catch (error) {
      console.error('获取任务状态失败:', error)
    }
  }

  // 立即检查一次
  await checkStatus()
  // 每5秒检查一次
  pollingTimer.value = setInterval(checkStatus, 5000)
}

// 添加下载视频方法
const downloadVideo = async () => {
  try {
    const response = await apiRequest(`/productAvatar/task/download?taskId=${currentTaskId.value}`, {
      method: 'GET'
    })

    if (response.code === 200 && response.data.downloadUrl) {
      // 创建一个临时链接并触发下载
      const link = document.createElement('a')
      link.href = response.data.downloadUrl
      link.download = `marketing_video_${currentTaskId.value}.mp4`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } else {
      throw new Error(response.msg || response.message || '获取下载链接失败')
    }
  } catch (error) {
    console.error('下载视频失败:', error)
    ElMessage.error('下载视频失败，请重试')
  }
}

// 完成后的操作
const viewVideoList = () => {
  router.push('/marketing-video/list')
}

// 在 script setup 顶部添加新的响应式变量
const currentTaskId = ref(null)
const pollingTimer = ref(null)
const ttsText = ref('')
const productReplaceResultKey = ref('')
const generatedImage = ref('')
const finishedVideoUrl = ref('')

// 音色选择相关
const showVoiceDialog = ref(false)
const voiceList = ref([])
const voiceoverId = ref('')
const currentPlayingVoice = ref(null)
const audioPlayer = ref(new Audio())
const genderFilter = ref('')
const ageFilter = ref('')
const voiceGridRef = ref(null)
const voiceLoading = ref(false)
const voicePageNo = ref(1)
const voiceHasMore = ref(true)
const languageFilter = ref('zh-CN') // 默认选择中文

// 计算属性：直接使用API返回的音色列表，不做前端过滤
const filteredVoiceList = computed(() => {
  console.log('filteredVoiceList 使用原始数据:', {
    voiceListLength: voiceList.value.length
  })
  // 直接返回API数据，不做前端过滤
  return voiceList.value
})

// 播放音色示例
const playVoiceDemo = (voice) => {
  // 只在文本转语音模式下才播放音色示例
  if (scriptMode.value !== 'tts') {
    return
  }
  
  if (!voice.demoAudioUrl) {
    ElMessage.warning('该音色暂无试听音频')
    return
  }

  if (currentPlayingVoice.value === voice.voiceId) {
    // 如果点击的是当前正在播放的音色，则停止播放
    audioPlayer.value.pause()
    audioPlayer.value.currentTime = 0
    currentPlayingVoice.value = null
  } else {
    // 如果之前有其他音色在播放，先停止
    if (currentPlayingVoice.value) {
      audioPlayer.value.pause()
      audioPlayer.value.currentTime = 0
    }
    
    // 播放新选择的音色
    audioPlayer.value.src = voice.demoAudioUrl
    audioPlayer.value.play()
    currentPlayingVoice.value = voice.voiceId
  }
}

// 选择音色
const handleSelectVoice = (voice) => {
  // 只在文本转语音模式下才设置音色
  if (scriptMode.value !== 'tts') {
    return
  }
  
  voiceoverId.value = voice.voiceId
}

// 确认音色选择
const confirmVoiceSelection = () => {
  // 只在文本转语音模式下才处理音色选择
  if (scriptMode.value !== 'tts') {
    return
  }
  
  if (voiceoverId.value) {
    // 停止音频播放
    audioPlayer.value.pause()
    audioPlayer.value.currentTime = 0
    currentPlayingVoice.value = null
    showVoiceDialog.value = false
  } else {
    ElMessage.warning('请选择一个音色')
  }
}

// 处理音色列表滚动
const handleVoiceScroll = (e) => {
  // 只在文本转语音模式下才处理音色列表滚动
  if (scriptMode.value !== 'tts') {
    return
  }
  
  const { scrollHeight, scrollTop, clientHeight } = e.target
  // 滚动到底部时加载更多
  if (scrollHeight - scrollTop - clientHeight < 50) {
    getVoiceList(true)
  }
}

// 监听筛选条件变化
watch([genderFilter, ageFilter, languageFilter], () => {
  // 只在文本转语音模式下才重新获取音色列表
  if (scriptMode.value === 'tts') {
    getVoiceList()
  }
})

// 修改音色选择框的点击事件
const handleVoiceSelect = async () => {
  // 只在文本转语音模式下才显示音色选择弹窗
  if (scriptMode.value !== 'tts') {
    return
  }
  
  console.log('打开音色弹窗，当前音色列表长度:', voiceList.value.length)
  showVoiceDialog.value = true
  
  // 如果音色列表为空或者筛选条件改变了，才重新获取数据
  if (voiceList.value.length === 0) {
    console.log('音色列表为空，重新获取音色数据...')
    await getVoiceList()
  } else {
    console.log('音色列表已存在，直接显示')
  }
}

// 获取人种列表
const getEthnicityList = async () => {
  try {
    ethnicityLoading.value = true
    const params = new URLSearchParams({
      scene: 'video_avatar'
    })
    
    const response = await apiRequest(`${API_CONFIG.ENDPOINTS.GET_ETHNICITY_LIST}?${params.toString()}`, {
        method: 'GET'
      })
      
    if (response && response.code === 200 && response.result && response.result.data) {
      // 英文到中文的翻译映射
      const ethnicityTranslations = {
        'Black or African American': '非洲裔美国人',
        'White (Western European)': '西欧白人',
        'White (Eastern European)': '东欧白人',
        'Hispanic or Latino': '西班牙裔/拉丁裔',
        'Middle Eastern or North African': '中东/北非',
        'East Asian': '东亚',
        'Southeast Asian': '东南亚',
        'South Asian': '南亚'
      }
      
      // 处理数据并翻译为中文
      ethnicityList.value = response.result.data.map(ethnicity => ({
        ...ethnicity,
        ethnicityName: ethnicityTranslations[ethnicity.ethnicityName] || ethnicity.ethnicityName
      }))
      
      // 设置默认选中"所有"
      if (!activeEthnicity.value) {
        activeEthnicity.value = 'all'
      }
    }
  } catch (error) {
    console.error('获取人种列表失败:', error)
    ElMessage.warning('获取人种列表失败')
  } finally {
    ethnicityLoading.value = false
  }
}
          
// 处理人种切换
const handleEthnicityChange = (ethnicityId) => {
  console.log('切换人种:', ethnicityId)
  activeEthnicity.value = ethnicityId
  // 重新获取该人种下的数字人列表
  pageNo.value = 0
  allAvatars.value = []
  fetchAvatarList()
}

// 页面加载
onMounted(async () => {
  console.log('营销视频生成页面开始加载...')
  
  // 检查路由参数，设置当前步骤
  const stepParam = route.query.step
  const taskIdParam = route.query.taskId
  
  console.log('路由参数:', { stepParam, taskIdParam })
  
  if (stepParam) {
    const step = parseInt(stepParam)
    if (step >= 1 && step <= 4) {
      currentStep.value = step
      console.log('设置当前步骤为:', step)
    }
  }
  
  if (taskIdParam) {
    currentTaskId.value = taskIdParam
    console.log('设置任务ID为:', taskIdParam)
    // 立即加载任务详情数据
    await loadTaskData(taskIdParam)
  }
  
  console.log('开始获取基础数据...')
  
  // 暂时只获取分类数据，其他的先注释掉
  try {
    await fetchCategories()
    console.log('分类数据获取完成')
  } catch (error) {
    console.error('获取分类数据失败:', error)
  }
  
  // 重新启用人种数据获取
  try {
    await getEthnicityList()
    console.log('人种数据获取完成')
  } catch (error) {
    console.error('获取人种数据失败:', error)
  }
  
  // 重新启用音色数据获取（只在文本转语音模式下）
  if (scriptMode.value === 'tts') {
    try {
      await getVoiceList()
      console.log('音色数据获取完成')
    } catch (error) {
      console.error('获取音色数据失败:', error)
    }
  }
  
  // 从localStorage恢复状态（如果有的话）
  const savedAvatar = localStorage.getItem('marketingAvatar')
  const savedImage = localStorage.getItem('marketingImage')
  const savedTask = localStorage.getItem('currentTaskId')
  
  console.log('本地存储状态:', { savedAvatar, savedImage, savedTask })
  
  if (savedAvatar) {
    try {
      selectedAvatar.value = JSON.parse(savedAvatar)
      console.log('恢复数字人数据成功')
    } catch (e) {
      console.error('解析保存的数字人数据失败:', e)
    }
  }
  
  if (savedImage) {
    try {
      selectedImage.value = JSON.parse(savedImage)
      console.log('恢复图片数据成功')
    } catch (e) {
      console.error('解析保存的图片数据失败:', e)
    }
  }
  
  if (savedTask) {
    try {
      currentTaskId.value = savedTask
      console.log('恢复任务ID成功')
    } catch (e) {
      console.error('解析保存的任务ID失败:', e)
    }
  }
  
  // 初始化数字人列表
  try {
    await fetchAvatarList()
    console.log('数字人列表初始化完成')
  } catch (error) {
    console.error('初始化数字人列表失败:', error)
  }
  
  console.log('营销视频生成页面加载完成！')
})

// 组件卸载时清理
onUnmounted(() => {
  if (selectedAvatar.value?.isCustom && selectedAvatar.value.imageUrl.startsWith('blob:')) {
    URL.revokeObjectURL(selectedAvatar.value.imageUrl)
  }
  if (selectedImage.value?.isLocalPreview) {
    URL.revokeObjectURL(selectedImage.value.url)
  }
  if (previewAudio.value?.url) {
    URL.revokeObjectURL(previewAudio.value.url)
  }
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }

  // 移除音频播放结束事件监听
  audioPlayer.value.removeEventListener('ended', () => {
    currentPlayingVoice.value = null
  })
  
  // 清理音频播放器
  audioPlayer.value.pause()
  audioPlayer.value.src = ''
})

// script部分
const imageEditPrompt = ref('')
const defaultPrompt = '示例：将图1中人员手中的物品替换为图2中的物品。保持图1中人物的构图位置和手势不变，并确保图2中项目的特征、外观和细节在更改后保持完全相同。'

const isGenerating = ref(false)

// 在 script 部分添加状态变量
const overallStatus = ref(0)

// 加载任务数据
const loadTaskData = async (taskId) => {
  try {
    const response = await apiRequest(`/productAvatar/task/detail?taskId=${taskId}`, {
      method: 'GET'
    })

    if (response.code === 200) {
      const taskInfo = response.data
      overallStatus.value = taskInfo.overall_status
      
      // 根据任务状态设置当前步骤
      if (overallStatus.value === 2) {
        // 图片生成完成，应该在步骤2
        currentStep.value = 2
        progress.value = 50
        
        // 设置生成的图片数据
        if (taskInfo.result_images) {
          if (Array.isArray(taskInfo.result_images) && taskInfo.result_images.length > 0) {
            const firstResult = taskInfo.result_images[0]
            if (firstResult && typeof firstResult === 'object') {
              productReplaceResultKey.value = firstResult.imageId || ''
              // 处理图片URL，添加尺寸限制参数
              generatedImage.value = `${firstResult.url}?x-oss-process=image/resize,m_fill,h_200,w_200`
            }
          }
        }
        
        // 设置营销文案（如果有的话，只在文本转语音模式下）
        if (taskInfo.tts_text && scriptMode.value === 'tts') {
          ttsText.value = taskInfo.tts_text
        }
        
        // 设置音色ID（如果有的话，只在文本转语音模式下）
        if (taskInfo.voiceover_id && scriptMode.value === 'tts') {
          voiceoverId.value = taskInfo.voiceover_id
        }
        
      } else if (overallStatus.value === 3) {
        // 视频生成中，应该在步骤3
        currentStep.value = 3
        progress.value = taskInfo.progress || 75
        // 开始轮询
        startPolling()
        
      } else if (overallStatus.value === 4) {
        // 视频生成完成，应该在步骤4
        currentStep.value = 4
        progress.value = 100
        
        // 设置生成的视频URL
        if (taskInfo.finished_video_url) {
          finishedVideoUrl.value = taskInfo.finished_video_url
        }
        
      } else if (overallStatus.value === 5) {
        // 生成失败
        ElMessage.error('任务生成失败')
      }
    }
  } catch (error) {
    console.error('加载任务数据失败:', error)
    ElMessage.error('加载任务数据失败')
  }
}

// 修改轮询状态的方法
const handleVoiceFilterChange = () => {
  // 只在文本转语音模式下才处理音色筛选条件变化
  if (scriptMode.value !== 'tts') {
    return
  }
  
  // 移除这里的调用，让 watch 监听器统一处理
  console.log('语言筛选条件改变，watch监听器会自动重新获取数据')
}

// 重新生成一个视频
const createAnother = () => {
  // 重置所有状态
  currentStep.value = 1
  currentTaskId.value = null
  selectedAvatar.value = null
  selectedImage.value = null
  scriptMode.value = 'tts' // 确保默认为文本转语音模式
  ttsText.value = ''
  voiceoverId.value = ''
  productReplaceResultKey.value = ''
  generatedImage.value = ''
  finishedVideoUrl.value = ''
  overallStatus.value = 0
  progress.value = 0
  isGenerating.value = false
  imageEditPrompt.value = ''
  
  // 重置音频相关状态
  if (previewAudio.value?.url) {
    URL.revokeObjectURL(previewAudio.value.url)
  }
  previewAudio.value = null
  
  // 清除本地存储
  localStorage.removeItem('marketingAvatar')
  localStorage.removeItem('marketingImage')
  localStorage.removeItem('currentTaskId')
  
  // 停止轮询
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }
  
  ElMessage.success('已重置，可以开始新的视频生成')
}

const handleVoiceDialogOpen = async () => {
  // 只在文本转语音模式下才获取音色数据
  if (scriptMode.value !== 'tts') {
    return
  }
  
  console.log('音色弹窗打开，强制刷新音色数据')
  // 每次打开弹窗都重新获取音色数据，确保数据正确显示
  await getVoiceList()
}

// 监听弹窗关闭
const handleVoiceDialogClose = () => {
  // 只在文本转语音模式下才处理音色相关逻辑
  if (scriptMode.value !== 'tts') {
    return
  }
  
  // 停止音频播放
  audioPlayer.value.pause()
  audioPlayer.value.currentTime = 0
  currentPlayingVoice.value = null
}

// 跳转到生成记录页面
function handleGoToRecords() {
  router.push('/marketing-video/list')
}
</script>

<style lang="scss" scoped>
.marketing-video-generate {
  min-height: 100vh;
  background: #141414;
  padding: 24px;
  padding-top: 100px;
  position: relative;

  /* 引导提示样式 */
  .guide-tip {
    position: absolute;
    top: 24px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    background: linear-gradient(135deg, #409eff, #66b1ff);
    border-radius: 12px;
    padding: 12px 24px;
    box-shadow: 0 8px 32px rgba(64, 158, 255, 0.3);
    animation: slideDown 0.5s ease-out;
    min-width: 600px;
  }

  .guide-content {
    display: flex;
    align-items: center;
    gap: 12px;
    color: white;
  }

  .guide-icon {
    font-size: 18px;
  }

  .guide-text {
    font-size: 13px;
    font-weight: 500;
    white-space: nowrap;
    flex: 1;
  }

  @keyframes slideDown {
    from {
      opacity: 0;
      transform: translateX(-50%) translateY(-20px);
    }
    to {
      opacity: 1;
      transform: translateX(-50%) translateY(0);
    }
  }

  /* 进度条样式 */
  .progress-bar {
    max-width: 800px;
    margin: 0 auto 40px;
    display: flex;
    justify-content: space-between;
    position: relative;
    padding: 0 40px;

    &::before {
      content: '';
      position: absolute;
      top: 24px;
      left: 50px;
      right: 50px;
      height: 2px;
      background: #2c2c2c;
      z-index: 1;
    }

    .step-item {
      position: relative;
      z-index: 2;
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 150px;

      .step-number {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: #1f1f1f;
        border: 2px solid #2c2c2c;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        color: #909399;
        margin-bottom: 8px;
        transition: all 0.3s ease;
      }

      .step-text {
        font-size: 14px;
        color: #909399;
        transition: all 0.3s ease;
      }

      &.active {
        .step-number {
          background: #409eff;
          border-color: #409eff;
          color: #fff;
        }
        .step-text {
          color: #409eff;
          font-weight: 500;
        }
      }

      &.completed {
        .step-number {
          background: #67c23a;
          border-color: #67c23a;
          color: #fff;
        }
        .step-text {
          color: #67c23a;
        }
      }
    }
  }

  /* 主内容区域样式 */
  .step-content {
    max-width: 95%;
    margin: 0 auto;
    background: #1f1f1f;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
    
    .main-content {
      display: flex;
      gap: 24px;
      padding: 20px;

        .left-panel {
          flex: 1;
          min-width: 0;
          max-width: calc(100% - 384px);
          position: relative;
          z-index: 1;

          .section-header {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            gap: 32px;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 1px solid #2c2c2c;
          }

          .section-title {
            font-size: 24px;
            font-weight: 600;
            color: #fff;
            margin: 0;
            letter-spacing: 0.5px;
          }

          .records-title {
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            color: #409eff;
            position: relative;
            padding: 4px 12px;
            border-radius: 6px;
            background: rgba(64, 158, 255, 0.1);
            border: 1px solid rgba(64, 158, 255, 0.3);
          }

          .records-title:hover {
            color: #66b1ff;
            background: rgba(64, 158, 255, 0.2);
            border-color: rgba(64, 158, 255, 0.5);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
          }

          .records-title::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 12px;
            right: 12px;
            height: 2px;
            background: #409eff;
            transform: scaleX(0);
            transition: transform 0.3s ease;
          }

          .records-title:hover::after {
            transform: scaleX(1);
          }

          .category-tabs {
          margin-bottom: 24px;

          .category-list {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            padding: 16px;
            background: #1f1f1f;
            border-radius: 8px;
            margin-bottom: 24px;

            .category-item {
              padding: 6px 16px;
              background: #141414;
              border: 1px solid #2c2c2c;
              border-radius: 20px;
              color: #909399;
              font-size: 14px;
              cursor: pointer;
              transition: all 0.3s;

              &:hover {
                border-color: #409eff;
                color: #409eff;
              }

              &.active {
                background: #409eff;
                border-color: #409eff;
                color: #fff;
              }
            }
          }
        }

        .ethnicity-section {
          margin-bottom: 24px;

          h4 {
            margin: 0 0 16px;
            font-size: 15px;
            color: #e0e0e0;
          }

          .ethnicity-list {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            padding: 16px;
            background: #1f1f1f;
            border-radius: 8px;

            .category-item {
              padding: 6px 16px;
              background: #141414;
              border: 1px solid #2c2c2c;
              border-radius: 20px;
              color: #909399;
              font-size: 14px;
              cursor: pointer;
              transition: all 0.3s;

              &:hover {
                border-color: #409eff;
                color: #409eff;
              }

              &.active {
                background: #409eff;
                border-color: #409eff;
                color: #fff;
              }

              &.disabled {
                cursor: not-allowed;
                opacity: 0.6;
              }
            }
          }
        }

        .avatar-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
          gap: 10px;
          padding: 8px;
          max-height: 600px;
          min-height: 400px;
          overflow-y: auto;
          overflow-x: hidden;
          background: #141414;
          border-radius: 8px;
          position: relative;

          .upload-card {
            background: #1f1f1f;
            border-radius: 8px;
            overflow: hidden;
            transition: all 0.3s ease;
            border: 1px solid #2c2c2c;
            cursor: pointer;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
              border-color: #409eff;
            }

            &.active {
              border-color: #409eff;
              box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
            }
          }

          .avatar-item {
            position: relative;
            overflow: hidden;
            border-radius: 12px;
            cursor: pointer;
            transition: transform 0.3s ease;
            border: 2px solid transparent;

            &:hover {
              transform: scale(1.02);
            }

            &.active {
              border-color: #409eff;
            }
          }

          .upload-card {
            .upload-content {
              height: 220px;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              color: #909399;
              gap: 12px;
              padding: 24px;

              .el-icon {
                font-size: 36px;
              }

              span {
                font-size: 16px;
              }
            }

            .custom-avatar-preview {
              position: relative;
              
              .avatar-image {
                width: 100%;
                height: 220px;
                object-fit: cover;
              }

              .avatar-info {
                padding: 16px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 12px;

                .avatar-name {
                  font-size: 14px;
                  color: #e0e0e0;
                  flex: 1;
                  min-width: 0;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
              }

              .change-photo-overlay {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                height: 220px;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                color: #fff;
                opacity: 0;
                transition: opacity 0.3s;
                gap: 8px;
                
                .el-icon {
                  font-size: 20px;
                }
                
                span {
                  font-size: 14px;
                }
              }

              &:hover .change-photo-overlay {
                opacity: 1;
              }
            }
          }

          .avatar-item {
            .avatar-image {
              width: 100%;
              height: 180px;
              object-fit: contain;
              border-radius: 12px;
              display: block;
              background: #18181c;
            }
          }
        }
      }

      .right-panel {
        width: 360px;
        flex-shrink: 0;
        position: relative;
        z-index: 1;

        .preview-section {
          background: #1f1f1f;
          border-radius: 8px;
          border: 1px solid #2c2c2c;
          overflow: hidden;

          h3 {
            margin: 0;
            padding: 20px 24px;
            font-size: 16px;
            font-weight: 500;
            color: #e0e0e0;
            border-bottom: 1px solid #2c2c2c;
          }

          .preview-container {
            height: 400px;
            width: 100%;
            max-width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #141414;
            padding: 24px;
            overflow: hidden;
            box-sizing: border-box;
            position: relative;
            
            .upload-placeholder {
              text-align: center;
              cursor: pointer;
              padding: 32px;
              
              .el-icon {
                font-size: 48px;
                margin-bottom: 16px;
              }
              
              .upload-text {
                margin-top: 20px;
                font-size: 16px;
                color: #909399;
              }
              
              .upload-hint {
                margin-top: 12px;
                font-size: 13px;
                color: #606266;
              }
            }

            .image-wrapper {
              width: 100%;
              height: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              overflow: hidden;
            }

            .no-preview {
              color: #909399;
              font-size: 14px;
              text-align: center;
            }
          }

          .note-box {
            padding: 24px;
            border-top: 1px solid #2c2c2c;

            .note-title {
              display: flex;
              align-items: center;
              gap: 12px;
              margin-bottom: 16px;
              color: #909399;
              font-size: 14px;

              .el-icon {
                color: #606266;
                font-size: 18px;
              }
            }

            :deep(.el-textarea) {
              .el-textarea__inner {
                background: #141414;
                border-color: #2c2c2c;
                color: #e0e0e0;
                padding: 12px 16px;
                font-size: 14px;
                line-height: 1.6;
                resize: none;

                &:focus {
                  border-color: #409eff;
                }

                &::placeholder {
                  color: #606266;
                }
              }
            }
          }

          .action-buttons {
            padding: 20px 24px;
            display: flex;
            justify-content: flex-end;
            gap: 16px;
            border-top: 1px solid #2c2c2c;

            :deep(.el-button) {
              padding: 12px 24px;
              font-size: 14px;

              &.next-btn {
                position: relative;
                padding-right: 80px !important;

                .points-text {
                  position: absolute;
                  right: 12px;
                  top: 50%;
                  transform: translateY(-50%);
                  font-size: 12px;
                  opacity: 1;
                  padding-left: 12px;
                  border-left: 1px solid rgba(255, 255, 255, 0.5);
                }
              }
            }
          }
        }

        // 步骤2的结果预览区域样式
        .result-preview-section {
          background: #1f1f1f;
          border-radius: 8px;
          border: 1px solid #2c2c2c;
          overflow: hidden;
          width: 100%;
          max-width: 100%;
          box-sizing: border-box;

          h3 {
            margin: 0;
            padding: 20px 24px;
            font-size: 16px;
            font-weight: 500;
            color: #e0e0e0;
            border-bottom: 1px solid #2c2c2c;
          }

          .preview-container {
            height: 400px;
            width: 100%;
            background: #141414;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .image-container {
              width: 200px;
              height: 200px;
              border: 1px solid #2c2c2c;
              border-radius: 4px;
            }

            .result-preview-image {
              max-width: 200px;
              max-height: 200px;
              width: auto;
              height: auto;
            }

            .no-preview {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              color: #909399;
              font-size: 14px;
              text-align: center;
            }
          }
        }
      }
    }
  }

  /* 生成中和完成页面样式 */
  .generating-content,
  .completed-content {
    min-height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    padding: 48px 24px;

    .generating-info,
      .completed-info {
    max-width: 600px;

    .generating-icon {
      color: #409eff;
      animation: rotate 2s linear infinite;
    }

    .success-icon {
      color: #67c23a;
    }

    h3 {
      margin: 24px 0 12px;
      font-size: 24px;
      color: #e0e0e0;
    }

    p {
      color: #909399;
      margin-bottom: 24px;
    }

    .video-preview-section {
      margin: 32px 0;
      text-align: center;

      h4 {
        margin: 0 0 16px;
        font-size: 18px;
        color: #e0e0e0;
      }

      .video-container {
        background: #141414;
        border-radius: 8px;
        padding: 20px;
        border: 1px solid #2c2c2c;

        .finished-video {
          width: 100%;
          max-width: 500px;
          border-radius: 4px;
          background: #000;
        }
      }
    }

    .progress {
      margin-top: 32px;
    }

    .action-buttons {
      margin-top: 32px;
      display: flex;
      justify-content: center;
      gap: 16px;
    }
  }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #141414;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #2c2c2c;
  border-radius: 4px;
  
  &:hover {
    background: #3c3c3c;
  }
}

/* 全局弹窗样式覆盖 */
:deep(.el-overlay) {
  background-color: rgba(0, 0, 0, 0.7) !important;
}

:deep(.el-overlay-dialog) {
  background-color: transparent !important;
}

:deep(.el-dialog) {
  border: none !important;
  background: #141414 !important;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5) !important;
}

.voice-dialog {
  :deep(.el-dialog) {
    background: #141414 !important;
    border: 1px solid #2c2c2c !important;
    border-radius: 8px;
    overflow: hidden;
    margin-top: 8vh !important;
    
    .el-dialog__header {
      margin: 0;
      padding: 24px;
      border-bottom: 1px solid #2c2c2c;
      background: #141414;

      .el-dialog__title {
        font-size: 18px;
        font-weight: 500;
        color: #e0e0e0;
      }

      .el-dialog__close {
        color: #909399;
        &:hover {
          color: #e0e0e0;
        }
      }
    }

    .el-dialog__body {
      padding: 0 !important;
      background: #141414;
      color: #e0e0e0;
    }

    .el-dialog__footer {
      margin-top: 0;
      padding: 20px 24px;
      border-top: 1px solid #2c2c2c;
      background: #141414;

      .dialog-footer {
        .el-button {
          background: #141414;
          border: 1px solid #2c2c2c;
          color: #e0e0e0;

          &:hover {
            border-color: #409eff;
            color: #409eff;
          }

          &.el-button--primary {
            background: #409eff;
            border-color: #409eff;
            color: #fff;

            &:hover {
              background-color: #66b1ff;
              border-color: #66b1ff;
            }
          }
        }
      }
    }
  }

  .voice-filter {
    padding: 20px 24px;
    background: #141414;
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;

    :deep(.el-radio-group) {
      display: flex;
      gap: 12px;

      .el-radio-button__inner {
        background: #141414;
        border-color: #2c2c2c;
        color: #e0e0e0;
        box-shadow: none;

        &:hover {
          color: #409eff;
        }
      }

      .el-radio-button__original-radio:checked + .el-radio-button__inner {
        background: #409eff;
        border-color: #409eff;
        color: #fff;
        box-shadow: -1px 0 0 0 #409eff;
      }
    }

    .language-select {
      min-width: 220px !important;
    }
  }

  .voice-grid {
    background: #141414;
    padding: 0 24px 24px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    max-height: 60vh;
    overflow-y: auto;

    .voice-card {
      background: #1a1a1a;
      border-radius: 8px;
      padding: 16px;
      cursor: pointer;
      transition: all 0.3s;
      border: 1px solid #2c2c2c;
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #e0e0e0;

      &:hover {
        transform: translateY(-2px);
        border-color: #409eff;
      }

      &.active {
        border-color: #409eff;
        box-shadow: 0 0 0 1px #409eff;
      }

      .voice-info {
        flex: 1;

        .voice-name {
          font-size: 16px;
          font-weight: 500;
          color: #e0e0e0;
          margin-bottom: 8px;
        }

        .voice-tags {
          display: flex;
          gap: 8px;
          flex-wrap: wrap;

          :deep(.el-tag) {
            background: #141414;
            border-color: #2c2c2c;
            color: #e0e0e0;
            
            &.el-tag--info {
              background: #141414;
              border-color: #2c2c2c;
            }

            &.el-tag--success {
              background: #67c23a;
              border-color: #67c23a;
              color: #fff;
            }

            &.el-tag--warning {
              background: #e6a23c;
              border-color: #e6a23c;
              color: #fff;
            }

            &.el-tag--danger {
              background: #f56c6c;
              border-color: #f56c6c;
              color: #fff;
            }
          }
        }
      }

      .voice-preview {
        .preview-btn {
          font-weight: 600 !important;
          letter-spacing: 1px !important;
          padding: 8px 16px !important;
          display: flex !important;
          align-items: center !important;
          gap: 4px !important;
        }

        .preview-btn :deep(.el-icon) {
          margin-right: 2px !important;
        }
      }
    }
  }

  .loading-more {
    background: #141414;
    margin: 0 24px 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    color: #909399;
    font-size: 14px;
    gap: 12px;

    .el-icon {
      font-size: 18px;
    }
  }
}

/* Element Plus 组件全局样式覆盖 */
:deep(.el-button) {
  height: auto;
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.3s ease;
  background-color: #141414 !important;
  border: 1px solid #2c2c2c !important;
  color: #e0e0e0 !important;

  &:hover {
    background-color: #1a1a1a !important;
    border-color: #409eff !important;
  }

  &.el-button--default {
    background-color: #141414 !important;
    border-color: #2c2c2c !important;
    color: #e0e0e0 !important;

    &:hover {
      background-color: #1a1a1a !important;
      border-color: #409eff !important;
    }
  }

  &.el-button--primary {
    background-color: #409eff !important;
    border-color: #409eff !important;
    color: #fff !important;

    &:hover {
      background-color: #66b1ff !important;
      border-color: #66b1ff !important;
    }
  }

  &.el-button--danger {
    background-color: #f56c6c !important;
    border-color: #f56c6c !important;
    color: #fff !important;

    &:hover {
      background-color: #f78989 !important;
      border-color: #f78989 !important;
    }
  }

  .el-icon {
    font-size: 16px;
  }

  & + .el-button {
    margin-left: 16px;
  }
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  background-color: #141414 !important;
  box-shadow: 0 0 0 1px #2c2c2c inset !important;
  border: none !important;
  color: #e0e0e0 !important;

  &:hover {
    box-shadow: 0 0 0 1px #409eff inset !important;
  }

  &.is-focus {
    box-shadow: 0 0 0 1px #409eff inset !important;
  }

  .el-input__inner {
    color: #e0e0e0 !important;
    background-color: transparent !important;
  }
}

:deep(.el-select) {
  .el-input {
    .el-input__wrapper {
      background-color: #141414 !important;
      box-shadow: 0 0 0 1px #2c2c2c inset !important;
      border: none !important;
      color: #e0e0e0 !important;
      
      &:hover {
        box-shadow: 0 0 0 1px #409eff inset !important;
      }
      
      .el-input__inner {
        color: #e0e0e0 !important;
        background-color: transparent !important;
      }
      
      .el-select__caret {
        color: #909399 !important;
      }
    }
  }
}

:deep(.el-select-dropdown) {
  background-color: #141414 !important;
  border: 1px solid #2c2c2c !important;
  
  .el-select-dropdown__item {
    color: #e0e0e0 !important;
    
    &:hover {
      background-color: #1a1a1a !important;
    }
    
    &.selected {
      background-color: #409eff !important;
      color: #fff !important;
    }
  }
}

:deep(.el-popper.is-light) {
  background-color: #141414 !important;
  border-color: #2c2c2c !important;
  
  .el-popper__arrow::before {
    background-color: #141414 !important;
    border-color: #2c2c2c !important;
  }
}

.edit-section {
  h3 {
    margin: 0 0 24px;
    font-size: 18px;
    color: #e0e0e0;
  }



  .script-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h4 {
      margin: 0;
      font-size: 18px;
      color: #e0e0e0;
      font-weight: 600;
    }

    :deep(.el-button-group) {
      display: flex !important;
      border-radius: 8px !important;
      overflow: hidden !important;
      
      .el-button {
        background-color: #23232a !important;
        border-color: #2a2a2a !important;
        color: #e0e0e0 !important;
        transition: all 0.3s ease !important;
        border-radius: 0 !important;
        margin: 0 !important;
        
        &:first-child {
          border-top-left-radius: 8px !important;
          border-bottom-left-radius: 8px !important;
        }
        
        &:last-child {
          border-top-right-radius: 8px !important;
          border-bottom-right-radius: 8px !important;
        }
        
        &:hover {
          background-color: #2a2a2a !important;
          border-color: #409eff !important;
          color: #409eff !important;
        }
        
        &.is-active,
        &.el-button--primary {
          background-color: #409eff !important;
          border-color: #409eff !important;
          color: #fff !important;
          box-shadow: 0 0 0 1px #409eff !important;
          transform: translateY(-1px) !important;
        }
      }
    }
  }

  .audio-section {
    margin-bottom: 32px;
    
    h4 {
      margin: 0 0 16px;
      font-size: 15px;
      color: #e0e0e0;
    }

    :deep(.el-select) {
      width: 100%;
      
      .el-input {
        .el-input__wrapper {
          background-color: #141414 !important;
          box-shadow: 0 0 0 1px #2c2c2c inset !important;
          border: none !important;
          color: #e0e0e0 !important;
          
          &:hover {
            box-shadow: 0 0 0 1px #409eff inset !important;
          }
          
          .el-input__inner {
            color: #e0e0e0 !important;
            background-color: transparent !important;
          }
          
          .el-select__caret {
            color: #909399 !important;
          }
        }
      }
    }

    :deep(.el-textarea__inner) {
      background: #18181c !important;
      border: 1px solid #2a2a2a !important;
      border-radius: 8px;
      color: #e0e0e0 !important;
      padding: 16px;
      font-size: 14px;
      line-height: 1.6;
      min-height: 600px !important;
      
      &:focus {
        border-color: #409eff !important;
      }
      
      &::placeholder {
        color: #606266;
      }
    }

    .voice-select {
      margin-bottom: 20px;
      width: 100%;
    }
  }

  .audio-upload-section {
    margin-bottom: 20px;
    height: 400px;
    display: flex;
    flex-direction: column;

    .file-input {
      display: none;
    }

    .upload-placeholder {
      border: 2px dashed #2a2a2a;
      border-radius: 12px;
      padding: 40px 20px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s ease;
      background: #141414;
      color: #909399;
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      min-height: 300px;

      &:hover {
        border-color: #409eff;
        background: #18181c;
      }

      .el-icon {
        color: #909399;
        margin-bottom: 16px;
      }

      .upload-text {
        font-size: 16px;
        color: #e0e0e0;
        margin-bottom: 8px;
      }

      .upload-hint {
        font-size: 12px;
        opacity: 0.7;
        color: #909399;
      }
    }

    .audio-preview {
      background: #141414;
      border: 1px solid #2c2c2c;
      border-radius: 8px;
      padding: 20px;
      flex: 1;
      display: flex;
      flex-direction: column;
      min-height: 300px;

      .audio-info {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 16px;
        color: #e0e0e0;

        .el-icon {
          color: #409eff;
          font-size: 20px;
        }

        .audio-name {
          color: #e0e0e0;
          font-size: 14px;
          flex: 1;
        }
      }

      .audio-player {
        width: 100%;
        max-width: 400px;
        margin-bottom: 16px;
        flex: 1;
      }

      .audio-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: auto;
      }
    }
  }

  :deep(.el-select-dropdown) {
    background-color: #141414 !important;
    border: 1px solid #2c2c2c !important;
    
    .el-select-dropdown__item {
      color: #e0e0e0 !important;
      
      &:hover {
        background-color: #1a1a1a !important;
      }
      
      &.selected {
        background-color: #409eff !important;
        color: #fff !important;
      }
    }
  }

  :deep(.el-popper.is-light) {
    background-color: #141414 !important;
    border-color: #2c2c2c !important;
    
    .el-popper__arrow::before {
      background-color: #141414 !important;
      border-color: #2c2c2c !important;
    }
  }

  .mode-select {
    margin-bottom: 20px;
    padding: 16px 24px;
    display: flex;
    align-items: center;
    gap: 8px;

    :deep(.el-radio) {
      margin-right: 24px;
      .el-radio__label {
        color: #e0e0e0;
      }
      &.is-checked {
        .el-radio__label {
          color: #409eff;
        }
      }
    }

    .help-icon {
      color: #909399;
      font-size: 16px;
      cursor: help;
      transition: color 0.3s;

      &:hover {
        color: #409eff;
      }
    }
  }

  .action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    margin-top: 24px;

    :deep(.el-button) {
      background-color: #141414 !important;
      border: 1px solid #2c2c2c !important;
      color: #e0e0e0 !important;

      &:hover {
        background-color: #1a1a1a !important;
        border-color: #409eff !important;
      }

      &.el-button--primary {
        background-color: #409eff !important;
        border-color: #409eff !important;
        color: #fff !important;

        &:hover {
          background-color: #66b1ff !important;
          border-color: #66b1ff !important;
        }
      }
    }
  }
}

.voice-select-wrapper {
  margin-bottom: 20px;

  .voice-select-btn {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #18181c;
    border: 1px solid #2a2a2a;
    color: #e0e0e0;
    padding: 8px 16px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;

    &:hover {
      background-color: #23232a;
      border-color: #409eff;
    }

    .el-icon {
      margin-left: 8px;
      font-size: 14px;
      color: #909399;
    }
  }
}
</style> 